﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Web.UI.WebControls;
using eBusiness.App_DAL;
using eBusiness.Models;

namespace eBusiness.Areas.Admin.Controllers
{
    [Authorize]
    public class NewsController : Controller
    {
        private readonly UnitOfWork _unitOfWork = new UnitOfWork();
        //
        // GET: /News/

        public ViewResult Index(int? pageNumber = 1, int? pageSize = 5, string softField = "CreatedDate", string softDir = "DESC")
        {
            ViewBag.CurrentSoftField = softField;
            ViewBag.CurrentSoftDir = softDir;

            var softdir = new List<ListItem> { new ListItem("Desc", "DESC"), new ListItem("Asc", "ASC") };
            ViewBag.SoftDir = new SelectList(softdir, softDir);

            var softFields = new List<ListItem>
                                 {
                                     new ListItem("Title", "Title"),
                                     new ListItem("ModifiedDate", "ModifiedDate"),
                                 };
            //ViewBag.SoftFields = new SelectList(softFields, Session["SoftField"]);
            ViewBag.SoftFields = new SelectList(softFields, softField);

            //apply filtering for get list product

            var filterExpressions = new Collection<Expression<Func<News, bool>>>();

            Expression<Func<News, bool>> expressionLeft = (n => n.IsDeleted == false);

            filterExpressions.Add(expressionLeft);

            Func<IQueryable<News>, IOrderedQueryable<News>> orderby = (n => n.OrderByDescending(o => o.CreatedDate));

            switch (softDir.ToUpper())
            {
                case "ASC":
                    if (softField != null && !string.IsNullOrEmpty(softField))
                    {
                        switch (softField)
                        {
                            case "Title":
                                orderby = (product => product.OrderBy(p => p.Title));
                                break;
                            case "ModifiedDate":
                                orderby = (product => product.OrderBy(p => p.ModifiedDate));
                                break;
                            default:
                                orderby = (product => product.OrderBy(p => p.CreatedDate));
                                break;
                        }
                    }
                    break;
                case "DESC":
                    if (softField != null && !string.IsNullOrEmpty(softField))
                    {
                        switch (softField)
                        {
                            case "Title":
                                orderby = (product => product.OrderByDescending(p => p.Title));
                                break;
                            case "ModifiedDate":
                                orderby = (product => product.OrderByDescending(p => p.ModifiedDate));
                                break;
                            default:
                                orderby = (product => product.OrderByDescending(p => p.CreatedDate));
                                break;
                        }
                    }
                    break;
            }
            var news = _unitOfWork.NewsRepository.Get(filters: filterExpressions, orderby: orderby);

            long numberOfRecord = news.Count();

            long numberOfPage = numberOfRecord % pageSize == 0
                                   ? numberOfRecord / pageSize.Value
                                   : numberOfRecord / pageSize.Value + 1;

            ViewBag.NumberOfPage = numberOfPage;
            ViewBag.CurrentPage = pageNumber;

            news = _unitOfWork.NewsRepository.Get(filters: filterExpressions, orderby: orderby, pageSize: pageSize, pageNumber: pageNumber);

            return View(news.ToList());
        }

        //
        // GET: /News/Details/5

        public ViewResult Details(long id)
        {
            News news = _unitOfWork.NewsRepository.GetByID(id);
            return View(news);
        }

        //
        // GET: /News/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /News/Create

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(News news)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    news.ModifiedDate = DateTime.Now;
                    news.CreatedDate = DateTime.Now;
                    var membershipUser = Membership.GetUser();
                    if (membershipUser != null)
                    {
                        var providerUserKey = membershipUser.ProviderUserKey;
                        if (providerUserKey != null)
                        {
                            news.CreatedBy = (Guid)providerUserKey;
                            news.ModifiedBy = (Guid)providerUserKey;
                        }
                    }

                    news.IsDeleted = false;

                    for (int i = 0; i < Request.Files.Count; i++)
                    {
                        var hpf = Request.Files[i] as HttpPostedFileBase;
                        if (hpf != null)
                        {
                            if (hpf.ContentLength == 0)
                                continue;

                            string savedFileName = AppDomain.CurrentDomain.BaseDirectory +
                                                   "\\Content\\images\\news\\" + Path.GetFileName(hpf.FileName);
                            hpf.SaveAs(savedFileName);

                            news.ThumbImage = "/Content/images/news/" + Path.GetFileName(hpf.FileName);
                        }
                    }

                    _unitOfWork.NewsRepository.Insert(news);
                    _unitOfWork.Save();

                    return RedirectToAction("Index");
                }

                return View(news);

            }
            catch (Exception)
            {
                return View("Error");
            }
        }

        //
        // GET: /News/Edit/5

        public ActionResult Edit(long id)
        {
            News news = _unitOfWork.NewsRepository.GetByID(id);
            return View(news);
        }

        //
        // POST: /News/Edit/5

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(News news)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    news.ModifiedDate = DateTime.Now;
                    var membershipUser = Membership.GetUser();
                    if (membershipUser != null)
                    {
                        var providerUserKey = membershipUser.ProviderUserKey;
                        if (providerUserKey != null)
                        {
                            news.ModifiedBy = (Guid)providerUserKey;
                        }
                    }

                    for (int i = 0; i < Request.Files.Count; i++)
                    {
                        var hpf = Request.Files[i] as HttpPostedFileBase;
                        if (hpf != null)
                        {
                            if (hpf.ContentLength == 0)
                                continue;

                            string savedFileName = AppDomain.CurrentDomain.BaseDirectory +
                                                   "\\Content\\images\\news\\" + Path.GetFileName(hpf.FileName);
                            hpf.SaveAs(savedFileName);

                            news.ThumbImage = "/Content/images/news/" + Path.GetFileName(hpf.FileName);
                        }
                    }

                    _unitOfWork.NewsRepository.Update(news);
                    _unitOfWork.Save();
                    return RedirectToAction("Index");
                }

                return View(news);
            }
            catch (Exception)
            {
                return View("Error");
            }
        }

        //
        // GET: /News/Delete/5

        public ActionResult Delete(long id)
        {
            News news = _unitOfWork.NewsRepository.GetByID(id);

            return View(news);
        }

        //
        // POST: /News/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(long id)
        {
            try
            {
                News news = _unitOfWork.NewsRepository.GetByID(id);
                news.IsDeleted = true;
                _unitOfWork.NewsRepository.Update(news);
                _unitOfWork.Save();

                return RedirectToAction("Index");
            }
            catch (Exception)
            {
                return View("Error");
            }
        }

        protected override void Dispose(bool disposing)
        {
            _unitOfWork.Dispose();
        }
    }
}